import { Constructor, ECSEventSet } from "../ECSWorld";
import { ECSEvent } from "./ECSEvent";

/**
 * 预定义的空事件集合
 */
const EMPTY: ECSEvent[] = [];


export class ECSEventSetImpl implements ECSEventSet {
    private events = new Map<string, ECSEvent[]>();

    push(event: ECSEvent): void {
        const name = event.name;

        if (typeof name !== "string" || name.length === 0) {
            throw new Error(
                `[ECS] event '${event}' not set name by @ecsclass`
            );
        }

        let list = this.events.get(name);
        if (!list) {
            list = [];
            this.events.set(name, list);
        }
        if (event.unique) {
            list.length = 0;
        }
        list.push(event);
    }

    fetch<T extends ECSEvent>(constructor: Constructor<T>): T[] {
        const events = this.events.get(constructor.name);
        return events ? (events as T[]) : (EMPTY as T[]);
    }

    has<T extends ECSEvent>(constructor: Constructor<T>): boolean {
        const events = this.events.get(constructor.name);
        return events ? events.length > 0 : false;
    }

    clear(): void {
        this.events.clear();
    }
}